package com.wonder.app.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.domain.Adminuser;
import com.wonder.admin.mapper.AdminuserDao;
import com.wonder.admin.service.AdminuserService;
import com.wonder.app.domain.PrdInstock;
import com.wonder.app.domain.Serial;
import com.wonder.app.domain.Tray;
import com.wonder.app.mapper.PrdInstockDao;
import com.wonder.app.mapper.SerialDao;
import com.wonder.app.mapper.TrayDao;
import com.wonder.app.service.SerialService;
import com.wonder.app.service.TrayService;
import com.wonder.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SerialServiceImpl extends ServiceImpl<SerialDao, Serial> implements SerialService {

    private static final Logger _logger = LoggerFactory.getLogger(SfcOperpServiceImpl.class);
    @Autowired
    private  AdminuserService adminuserService;
    @Autowired
    private AdminuserDao adminuserDao;
    @Autowired
    private TrayService trayService;
    @Autowired
    private TrayDao trayDao;
    @Autowired
    private SerialDao serialDao;
    @Autowired
    private SerialService serialService;

    @Autowired
    private PrdInstockDao prdInstockDao;


    /**
     * 获取流水号
     * @param userid
     * @return
     */
    public Map<String,Object> getSerial(Long userid ,Map<String,Object> map)throws Exception{
        //先查询托盘有没有流水号，没有的话做新增
        String trayNo = VtuzxUtil.getString(map,"trayNo");
        String fspecification = VtuzxUtil.getString(map,"fspecification");
        Pattern pattern = Pattern.compile("[a-zA-Z]");
        Matcher matcher = pattern.matcher(fspecification);
        if (matcher.find()){
            fspecification = fspecification.substring(0,matcher.start());
        }

        Tray tray = trayDao.selectOne(new LambdaQueryWrapper<Tray>()
                .eq(Tray::getFBILLNO, trayNo));
        Map<String,Object> data = new HashMap<>();

        //查询入库单的入库日期,如果有的话返回入库日期，没有的话返回当前日期
        PrdInstock prdInstock = prdInstockDao.selectOne(new LambdaQueryWrapper<PrdInstock>()
                .eq(PrdInstock::getTRAYNO, trayNo)
                .eq(PrdInstock::getFWORKSHOPNAME,"机加车间")
                .eq(PrdInstock::getFSTATE, "audit"));
        if (!VtuzxUtil.isEmpty(prdInstock)){
            data.put("prdInstockTime",DateUtils
                    .dateToStr(prdInstock.getAUDITTIME(),"yyyy-MM-dd HH:mm:ss"));
        } else {
            data.put("prdInstockTime",DateUtils
                    .dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (!VtuzxUtil.isEmpty(tray.getSERIAL())){//说明当前有流水号

            data.put("serialNo",tray.getSERIAL());
            data.put("inStockTime",tray.getINSTOCKTIME());//这个是托盘表上的入库日期
            data.put("flot",tray.getFLOT());
            data.put("operNo",tray.getFOPERPNO());//工序计划


            return data;
        } else {//没有流水号做一个新增
            LocalDateTime now = LocalDateTime.now();//当前时间
            LocalTime cutoffTime = LocalTime.of(7,45);//7点45
            LocalDateTime startTime;
            LocalDateTime endTime;

            LocalDateTime todayCutoff = LocalDate.now().atTime(cutoffTime);

            if (now.isBefore(todayCutoff)) {
                // 当前时间在今天7:45之前
                startTime = todayCutoff.minusDays(1);
                endTime = todayCutoff.minusSeconds(1);
            } else {
                // 当前时间在今天7:45之后
                startTime = todayCutoff;
                endTime = todayCutoff.plusDays(1).minusSeconds(1);
            }

            //查询用户当前用户流水号
            Adminuser adminuser = adminuserService.getById(userid);
            String serialNo = "";
            Serial addserial = new Serial();
            if (VtuzxUtil.isEmpty(adminuser.getSerial()) ){
                throw new RuntimeException("当前用户没有流水号标识");
            }else {
                String userSerial = adminuser.getSerial();
                //判断日期，如果在当天的7点45之前，开始时间就是前一天的7点45到今天的7点44分59秒
                //如果在7点45之后，开始时间就是今天的7点45到第二天的7点44分59秒

                Date localToStartTime = Date.from(startTime.atZone(ZoneId.systemDefault()).toInstant());
                Date localToEndTime = Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant());
                Date localToNow = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

                //查询当天日期所属用户最新的一条
                Serial serial1 = serialDao.selectOne(new LambdaQueryWrapper<Serial>()
                        .gt(Serial::getDate,localToStartTime)
                        .lt(Serial::getDate,localToEndTime)
                        .eq(Serial::getUserId, userid)
                        .eq(Serial::getSpecification,fspecification)
                        .orderByDesc(Serial::getDate)
                        .last("limit 1")
                );

//                String yyMMdd = DateUtils.dateToStr(localToNow, "yyyyMMdd");//当天日期YYDDMM格式
                String yyMMdd = getMonthDay(now);
                //如果当前日期所属用户没有数据
                if (VtuzxUtil.isEmpty(serial1)){
                    //添加一条新的数据
                    addserial.setDate(localToNow);
                    addserial.setUserId(userid);
                    addserial.setSerial(1);
                    addserial.setTray(trayNo);//托号
                    addserial.setSpecification(fspecification);
                    serialNo = yyMMdd + "-" +userSerial + "1";
                }else {//如果当天日期用户有数据
                    Integer maxSerial =  serial1.getSerial()+1;
                    addserial.setDate(localToNow);
                    addserial.setUserId(userid);
                    addserial.setSerial(maxSerial);
                    addserial.setTray(trayNo);
                    addserial.setSpecification(fspecification);
                    serialNo =yyMMdd + "-" + userSerial + maxSerial;
                }
                serialService.saveOrUpdate(addserial);
                //新增后保存到托盘数据中
                tray.setSERIAL(serialNo);
                trayService.updateById(tray);
            }
            data.put("serialNo",serialNo);
            data.put("inStockTime",tray.getINSTOCKTIME());
            data.put("flot",tray.getFLOT());
            data.put("operNo",tray.getFOPERPNO());//工序计划号


            return data;
        }

    }

    /**
     * 返回年月日,如果在7点45之前返回前一天，7点45之后返回当天
     * @param localDateTime
     * @return
     */
    private String getMonthDay (LocalDateTime localDateTime){
        // 今天的 7:45
        LocalDateTime sevenFortyFive = LocalDate.now().atTime(7, 45);
        LocalDate targetDate;
        if (localDateTime.isBefore(sevenFortyFive)){
            targetDate = LocalDate.now().minusDays(1);//前一天
        } else {
            targetDate = LocalDate.now();//今天
        }
        // 转成 Date
        Date localToNow = Date.from(targetDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        // 格式化日期 yyyyMMdd
        String yyMMdd = new SimpleDateFormat("yyyyMMdd").format(localToNow);
        return yyMMdd;

    }
}
